package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"time"
	"user-perm/cache"
	"user-perm/models"
	"user-perm/pkg"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	login_key := "login_key" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, login_key).Int()
	if errCount > 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误三次",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, login_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	token, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
	return
}
func UserAddRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	userrole := models.UserRole{
		Model: gorm.Model{},
		Uid:   uid,
		Rid:   rid,
	}
	err := models.DB.Create(&userrole).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
	}
}
func UserGetRole(c *gin.Context) {
	uid := c.Query("uid")
	//select * FROM roles
	//	LEFT JOIN user_roles on roles.id=user_roles.rid
	//	WHERE user_roles.uid=1
	var roles []models.Role
	err := models.DB.Table("roles").
		Joins("left join user_roles on roles.id=user_roles.rid").
		Where("user_roles.uid=?", uid).Find(&roles).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": roles,
		})
	}

}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rolenode := models.RoleNode{
		Model: gorm.Model{},
		Rid:   rid,
		Nid:   nid,
	}
	err := models.DB.Create(&rolenode).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "分配权限失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "分配权限成功",
			"data": rolenode,
		})
		return
	}
}
func RoleGetNode(c *gin.Context) {
	rid := c.Query("rid")
	var nodes []models.Node
	err := models.DB.Table("nodes").
		Joins("left join role_nodes on nodes.id=role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Find(&nodes).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "查询权限失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询权限成功",
			"data": nodes,
		})
		return
	}
}
func RoleList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var roles []models.Role
	list_key := "list_key" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Offset(offset).Limit(size).Find(&roles)
		cachedata, _ := json.Marshal(roles)
		cache.Rdb.Set(cache.Ctx, list_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &roles)
	}
	var total int64
	models.DB.Model(&roles).Count(&total)
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "分页查询成功",
		"data":  roles,
		"total": total,
	})

}
func RoleDetail(c *gin.Context) {
	id := c.Query("id")
	var role models.Role
	detail_key := "detail_key" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&role)
		cachedata, _ := json.Marshal(role)
		cache.Rdb.Set(cache.Ctx, detail_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &role)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询详情成功",
		"data": role,
	})
	return
}
